--- 新天光电直读水表, dtype(14) 9600,EVEN
module(..., package.seeall)

local logtag = "XT_GDZD"
local read_interval = 5000
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local read_command = '01030001000295CB'
-- 回复01 03 04 86 9F 00 01 22 95  == 00 01 86 9F =99999

function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    if udtu and tonumber(udtu.dtype) == 14 then sys.taskInit(init) end
end
local function process(d)
    if #d > 8 then
        local v_hex = (d:sub(6, 7)..d:sub(4, 5)):toHex()
        local val = tonumber(v_hex, 16)
        usrdata.update({val})
        lcd.LCD_DATA[3] = '水表读数:' .. (val or 'ERROR')
    end
end
function init()
    power.openBoost()
    sys.wait(500)
    while true do
        -- 读取数据
        sys.publish("UART_SENT_RDY_" .. uid, uid, read_command:fromHex())
        -- 等待串口回复
        log.warn(logtag, "间隔5秒等待串口数据")
        result, data = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, 5000)
        if result then
            if (data) then
                process(data)
                --process(("01 03 04 86 9F 00 01 22 95"):fromHex())
            end
            sys.wait(5000)
        else
            lcd.LCD_DATA[3] =  "XT_MOD NOREADY"
            --process(("01 03 04 86 9F 00 01 22 95"):fromHex())
        end
    end
end
